package com.heima.article.interceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @author Psycho
 * @create 2022-04-25-13:34
 */
@Slf4j
public class AppUserTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //先获取请求头里的id
        String userId = request.getHeader("userId");
        //判断获取的userId是否为空
        //再把请求头里的id存放在ThreadLocal里面
        Optional<String> optional = Optional.ofNullable(userId);    //jdk1.8的新方法
        if(optional.isPresent()){
            ApUser apUser = new ApUser();
            apUser.setId(Integer.parseInt(userId));
            AppUserThreadLocalUtil.setUser(apUser);
            log.info("wmTokenFilter设置用户信息到threadlocal中...");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("清理threadlocal...");
        AppUserThreadLocalUtil.clear();
    }
}